﻿package cn.sdjzu.exercise;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.achartengine.chart.AbstractChart;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sdjzu.exercise.db.DBHelper;
import cn.sdjzu.exercise.myview.Ball;

@SuppressLint("HandlerLeak")
public class ExerciseActivity extends TransmissionActivity implements
		OnClickListener {
	private TextView mSettingForce;
	private TextView mGroupNum;
	private TextView mTimes;
	private TextView mCountdown5;
	private Button mBackBtn;
	private Button mAdjustSeatBtn;
	private Button mPauseBtn;
	private Button mStopBtn;
	private int groupNumMax;
	private boolean isLineRunning;//线正在移动标志
	private boolean ClickStopButtonFlag=false;//点击终止训练	标志
	private boolean countdownFinishFlg = false;//计数完成标志
	private boolean CountdownINGFlg = false;//正在计数
	private boolean[] hasPaused4MoveImg;
	private boolean[] hasPaused4SendData;
	private int[] sleepTime;
	private int[] perGroupSportCnt; // 每组的锻炼次数。
	private double[] forcePercent;
	public static String currentExerciseMode = "";
	public static String readCurrentForceFromDevice;
	ExerciseApp mApp;
	private SendDataThread sendDataThread;
	private LineMoveThread lineMoveThread;
	private int whichGroupIsRunningFinished = 0;
	Ball ball;
	int Bally;
	private FrameLayout frameLayout = null;
	MyView view = null;
	Bundle extras = null;
	AbstractChart mChart = null;
	FileInputStream localStream = null;
	private Button mIncreaseBtn;
	private Button mDecreaseBtn;
	private Button mSettingsBtn;
	static final int COUNT_DOWN54321 = 0;
	static final int COUNT_DOWN54321_FINISH = 1;
	static final int MOVE_IMAGE = 2;
	static final int UPDATE_HEADER_TEXT = 3;
	static final int SEND_FAILED = 4;
	static final int MOVE_LINE = 5;
	static final int UPDATE_LINE_HEADER_TEXT = 6;
	static final int COUNT_ready = 7;
	DBHelper dbtest;
	private int sendDataFlag = 0;
	ImageView myLineImageView1 = null;
	ImageView myLineImageView2 = null;
	Bitmap bitmap = null; // 自定义图片
	LinearLayout customizeChartLayout = null;
	float[] custome;
	int imageW;
	float xyscale;
	Toast defaultforce, defaultposition;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ExerciseApp.getInstance().addActivity(this);
		setContentView(R.layout.exercise);
		mApp = (ExerciseApp) ExerciseActivity.this.getApplication();
		DBNoDataToast = Toast
				.makeText(this, "请先测试最大位置与最大力量", Toast.LENGTH_LONG);
		defaultforce = Toast.makeText(this, "此处默认最大力量为100", Toast.LENGTH_LONG);
		defaultposition = Toast.makeText(this, "此处默认最大位置为100",
				Toast.LENGTH_LONG);
		mSettingForce = (TextView) findViewById(R.id.exercise_setting_force);
		mGroupNum = (TextView) findViewById(R.id.exercise_group_num);
		mTimes = (TextView) findViewById(R.id.exercise_times_num);
		mCountdown5 = (TextView) findViewById(R.id.exercise_countdown5);
		mBackBtn = (Button) findViewById(R.id.exercise_back);
		mAdjustSeatBtn = (Button) findViewById(R.id.exercise_adjust);
		mPauseBtn = (Button) findViewById(R.id.exercise_start_pause);
		mStopBtn = (Button) findViewById(R.id.exercise_stop);
		mIncreaseBtn = (Button) findViewById(R.id.exercise_increase);
		mDecreaseBtn = (Button) findViewById(R.id.exercise_decrease);
		mSettingsBtn = (Button) findViewById(R.id.exercise_settings);
		frameLayout = (FrameLayout) findViewById(R.id.exercise_img_ball);
		dbtest = new DBHelper(this);
		if (!MODE_CUSTOMIZE.equals(currentExerciseMode)) {
			try {
				maxForce = Integer.parseInt(dbtest.getDataFromDB(
						dbtest.TBL_USER_EXT, dbtest.TBL_USER_EXT_MAXFORCE,
						mApp.currentCardNo));
			} catch (NumberFormatException e) {
				DBNoDataToast.show();
				testPosAndForce("未测试最大力量！！！！", "默认力量为100");
			}
		}
		try {
			position = Integer.parseInt(dbtest.getDataFromDB(
					dbtest.TBL_USER_EXT, dbtest.TBL_USER_EXT_POSITION,
					mApp.currentCardNo));
		} catch (NumberFormatException e) {
			DBNoDataToast.show();
			testPosAndForce("未测试最大位置！！！！", "默认位置为100");
		}
		mIncreaseBtn.setOnClickListener(this);
		mDecreaseBtn.setOnClickListener(this);
		mSettingsBtn.setOnClickListener(this);
		mBackBtn.setOnClickListener(this);
		mAdjustSeatBtn.setOnClickListener(this);
		mPauseBtn.setOnClickListener(this);
		mStopBtn.setOnClickListener(this);
		custome = new float[8];
		Intent intent = new Intent();
		intent = getIntent();
		custome = intent.getFloatArrayExtra("custome");
		isLineRunning = false;
		ball = (Ball) findViewById(R.id.exercise_ball);
		ball.setVisibility(View.INVISIBLE);
		mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case COUNT_ready:
					mCountdown5.setText(String.valueOf(msg.obj));
					break;
				case COUNT_DOWN54321:
					mCountdown5.setText(String.valueOf(msg.obj));
					break;
				case COUNT_DOWN54321_FINISH:
					mCountdown5.setVisibility(View.GONE);
					ball.setVisibility(View.VISIBLE);
					break;
				// 线移动
				case MOVE_LINE:
					scrollLineCount++;
					// frameLayout.setBackgroundResource(R.drawable.span);
					if (scrollLineCount == ((int) (imageW * 1.5) + 1)) {
						mApp.isMove = false;
						// 初始化生成视图
						myLineImageView1 = new ImageView(ExerciseActivity.this);
						myLineImageView1.setImageBitmap(bitmap);
						LayoutParams newParams = new LayoutParams(
								initLeftMargin, secondParams);
						newParams.leftMargin = initLeftMargin / 2;
						newParams.topMargin = 40;
						myLineImageView1.setLayoutParams(newParams);
						frameLayout.addView(myLineImageView1);
					}
					int linex = scrollLineCount / scrollLineCountDiv;
					int liney = scrollLineCount % scrollLineCountDiv;
					int topTextUpdate = (scrollLineCount - scrollLineCountDiv / 2)
							% scrollLineCountDiv;
					if (topTextUpdate == 0) {
						exercise_count++;
						mTimes.setText(getResources().getString(
								R.string.exercise_time_num, exercise_count));
					}
					if (liney == 0) {
						if (linex % 2 == 0) {
							frameLayout.removeView(myLineImageView2);
							myLineImageView2 = null;
							myLineImageView2 = new ImageView(
									ExerciseActivity.this);
							myLineImageView2.setImageBitmap(bitmap);
							LayoutParams newParams = new LayoutParams(
									initLeftMargin, secondParams);
							newParams.leftMargin = initLeftMargin;
							newParams.topMargin = 40;
							myLineImageView2.setLayoutParams(newParams);
							myLineImageView2.invalidate();
							//myLineImageView2
							// .setBackgroundResource(R.drawable.span);
							frameLayout.addView(myLineImageView2);
							frameLayout.invalidate();
						} else {
							frameLayout.removeView(myLineImageView1);
							myLineImageView1 = null;
							myLineImageView1 = new ImageView(
									ExerciseActivity.this);
							myLineImageView1.setImageBitmap(bitmap);

							LayoutParams newParams = new LayoutParams(
									initLeftMargin, secondParams);
							newParams.leftMargin = initLeftMargin;
							newParams.topMargin = 40;
							myLineImageView1.setLayoutParams(newParams);
							myLineImageView1.invalidate();
							frameLayout.addView(myLineImageView1);
							frameLayout.invalidate();
						}
					}
					if (MODE_CUSTOMIZE.equals(currentExerciseMode)) {
						// 当为自定义模式时组数与次数与间歇时间，力量设定等的操作
						if (exercise_count == perGroupSportCnt[whichGroupIsRunningFinished]
								&& whichGroupIsRunningFinished < groupNumMax - 1) {
							whichGroupIsRunningFinished++;
							isPauseFlg = true;
							exercise_count = 1;
						} else if (exercise_count == perGroupSportCnt[whichGroupIsRunningFinished]
								&& whichGroupIsRunningFinished == groupNumMax - 1) {
							whichGroupIsRunningFinished = 0;
							isPauseFlg = true;
							exercise_count = 1;
							isLineRunning = false;
							mPauseBtn.setText(R.string.start);
							for (int i = 0; i < groupNumMax; i++) {
								hasPaused4MoveImg[i] = false;
							}
							hasPaused4SendData = hasPaused4MoveImg;
							isGroupRunningFinished = true;
						}
					} else {// 健身模式的四种选择时
						if ((exercise_count == perGroupSportCnt[whichGroupIsRunningFinished])
								&& (whichGroupIsRunningFinished == 0)) {
							//
							whichGroupIsRunningFinished = 1;
							isPauseFlg = true;
							exercise_count = 1; // exercise_count相同的情况下，有可能直接执行下面的
						} else if ((exercise_count == perGroupSportCnt[whichGroupIsRunningFinished])
								&& (whichGroupIsRunningFinished == 1)) {
							whichGroupIsRunningFinished = 2;
							isPauseFlg = true;
							exercise_count = 1; // exercise_count相同的情况下，有可能直接执行下面的
						} else if ((exercise_count == perGroupSportCnt[whichGroupIsRunningFinished])
								&& (whichGroupIsRunningFinished == 2)) {
							whichGroupIsRunningFinished = 3;
							isPauseFlg = true;
							exercise_count = 1; // exercise_count相同的情况下，有可能直接执行下面的
						} else if ((exercise_count == perGroupSportCnt[whichGroupIsRunningFinished])
								&& (whichGroupIsRunningFinished == 3)) {
							whichGroupIsRunningFinished = 4;
							isPauseFlg = true;
							exercise_count = 1; // exercise_count相同的情况下，有可能直接执行下面的
							if (MODE_ADD_MUSCLE.equals(currentExerciseMode)) { // 增肌模式
								whichGroupIsRunningFinished = 0;
								isPauseFlg = true;
								isLineRunning = false;
								mPauseBtn.setText(R.string.start);
								hasPaused4MoveImg[0] = false;
								hasPaused4MoveImg[1] = false;
								hasPaused4MoveImg[2] = false;
								hasPaused4MoveImg[3] = false;
								hasPaused4SendData = hasPaused4MoveImg;
								isGroupRunningFinished = true;
							}
						} else if ((exercise_count == perGroupSportCnt[whichGroupIsRunningFinished])
								&& (whichGroupIsRunningFinished == 4)) {
							whichGroupIsRunningFinished = 0;
							isPauseFlg = true;
							isLineRunning = false;
							exercise_count = 1; // exercise_count相同的情况下，有可能直接执行下面的
							mPauseBtn.setText(R.string.start);
							hasPaused4MoveImg[0] = false;
							hasPaused4MoveImg[1] = false;
							hasPaused4MoveImg[2] = false;
							hasPaused4MoveImg[3] = false;
							hasPaused4MoveImg[4] = false;
							hasPaused4SendData = hasPaused4MoveImg;
							isGroupRunningFinished = true; // 所有的完成标志，等待开始按钮按下。
						}
					}
					if (myLineImageView1 != null) {
						LayoutParams params = (LayoutParams) myLineImageView1
								.getLayoutParams();
						if (params.leftMargin > 0) {
							params.leftMargin -= moveLineLength;
							myLineImageView1.setLayoutParams(params);
							myLineImageView1.invalidate();
						} else {
							myLineImageView1.scrollBy(moveLineLength, 0);
							myLineImageView1.invalidate();
						}
					}

					if (myLineImageView2 != null) {
						LayoutParams params = (LayoutParams) myLineImageView2
								.getLayoutParams();
						if (params.leftMargin > 0) {
							params.leftMargin -= moveLineLength;
							myLineImageView2.setLayoutParams(params);
							myLineImageView2.invalidate();
						} else {
							myLineImageView2.scrollBy(moveLineLength, 0);
							myLineImageView2.invalidate();
						}
					}
					ball.bringToFront();
					break;

				case UPDATE_LINE_HEADER_TEXT:

					if (MODE_CUSTOMIZE.equals(currentExerciseMode)) {
						mSettingForce
								.setText(getResources()
										.getString(
												R.string.exercise_setting_force,
												(int)forcePercent[whichGroupIsRunningFinished]));
					} else {
						mSettingForce
								.setText(getResources()
										.getString(
												R.string.exercise_setting_force,
												(int) maxForce * forcePercent[whichGroupIsRunningFinished]));
					}
					mGroupNum.setText(getResources().getString(
							R.string.exercise_group_num,
							whichGroupIsRunningFinished + 1));
					exercise_count = 1;
					mTimes.setText(getResources().getString(
							R.string.exercise_time_num, exercise_count));

					// 消除上一组的View
					if (myLineImageView1 != null) {
						frameLayout.removeView(myLineImageView1);
						myLineImageView1 = null;
					}
					if (myLineImageView2 != null) {
						frameLayout.removeView(myLineImageView2);
						myLineImageView2 = null;
					}
					ball.cy = secondParams;
					ball.invalidate();
					ball.setVisibility(View.GONE);
					countdownFinishFlg = false;
					// 开启下一组的训练
					CountDownThread countDownThread = new CountDownThread();
					countDownThread.start();
					// 每组开始发送力量
					try {
						if (MODE_CUSTOMIZE.equals(currentExerciseMode)) {
							settingForce = (int) (forcePercent[whichGroupIsRunningFinished]);
						} else {
							settingForce = (int) (maxForce * forcePercent[whichGroupIsRunningFinished]);
						}
						mOutputStream.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, settingForce));
						sendDataFlag = 1;
						Thread.sleep(100);
					} catch (IOException e) {
						e.printStackTrace();
						IOMistake();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					break;
				case SEND_FAILED:
					Toast.makeText(ExerciseActivity.this, "send failed",
							Toast.LENGTH_LONG).show();
					break;
				default:
					break;
				}
			}
		};
	}

	boolean isPauseFlg = false;
	int scrollLineCount;
	int lineMoveCnt = 1;
	int moveLineLength = 1;
	int initLeftMargin;
	int scrollLineCountDiv;
	int scrollLineTime;
	int secondParams = 300;
	int mtop;
	int mbottom;

	public void initExercise() {
		// 取png图片
		String filePath = ExerciseActivity.this.getCacheDir().getAbsolutePath();
		File file = new File(filePath, "myview.png");
		try {
			localStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		bitmap = BitmapFactory.decodeStream(localStream);
		imageW = bitmap.getWidth();
		// 获取图片一次滚动的时间
		if (MODE_CUSTOMIZE.equals(currentExerciseMode)) {
			float i = custome[4] + custome[5] + custome[6] + custome[7];
			scrollLineTime = (int) (i / 2) * (1000 / imageW);
			// 获取数据库存储的自定义组数
			groupNumMax = (int) custome[2];
		} else if (MODE_ADD_MUSCLE.equals(currentExerciseMode)) {
			scrollLineTime = (int) (6.5) * (1000 / imageW);
		} else if (MODE_REDUCE_FAT.equals(currentExerciseMode)) {
			scrollLineTime = (int) (4) * (1000 / imageW);
		} else if (MODE_BODYBUILDING.equals(currentExerciseMode)
				|| (mode_ConstantSpeed_active.equals(currentExerciseMode))
				|| (mode_ConstantSpeed_passive.equals(currentExerciseMode))
				|| (mode_ConstantForce_active.equals(currentExerciseMode))
				|| (mode_ConstantForce_passive.equals(currentExerciseMode))) {
			scrollLineTime = (int) (4) * (1000 / imageW);
		} else if (MODE_ADD_FORCE.equals(currentExerciseMode)) {
			scrollLineTime = (int) (5) * (1000 / imageW);
		}
		scrollLineCountDiv = imageW;
		initLeftMargin = imageW;
		scrollLineCount = (int) (imageW * 1.5);
	}

	@Override
	public void onResume() {
		initExercise();
		Log.d(TAG, "ExerciseActivity onResume");
		isLineRunning = false;
		if (sendDataThread != null) {
			sendDataThread.interrupt();
		}
		if (MODE_ADD_FORCE.equals(currentExerciseMode)) {
			groupNumMax = 5;
			hasPaused4MoveImg = new boolean[groupNumMax];
			hasPaused4MoveImg[0] = false;
			hasPaused4MoveImg[1] = false;
			hasPaused4MoveImg[2] = false;
			hasPaused4MoveImg[3] = false;
			hasPaused4MoveImg[4] = false;
			hasPaused4SendData = hasPaused4MoveImg;
			sleepTime = new int[groupNumMax];
			sleepTime[0] = 0;
			sleepTime[1] = 60;
			sleepTime[2] = 70;
			sleepTime[3] = 80;
			sleepTime[4] = 80;
			forcePercent = new double[groupNumMax];
			forcePercent[0] = 0.8;
			forcePercent[1] = 0.85;
			forcePercent[2] = 0.9;
			forcePercent[3] = 0.95;
			forcePercent[4] = 1.0;
			perGroupSportCnt = new int[groupNumMax]; // 锻炼次数
			perGroupSportCnt[0] = 6;
			perGroupSportCnt[1] = 5;
			perGroupSportCnt[2] = 4;
			perGroupSportCnt[3] = 3;
			perGroupSportCnt[4] = 2;

			mSettingForce
			.setText(getResources()
					.getString(
							R.string.exercise_setting_force,
							(int) (maxForce * forcePercent[whichGroupIsRunningFinished])));
			mIncreaseBtn.setVisibility(View.GONE);
			mDecreaseBtn.setVisibility(View.GONE);
			mSettingsBtn.setVisibility(View.GONE);

		} else if (MODE_ADD_MUSCLE.equals(currentExerciseMode)) {

			groupNumMax = 4;
			hasPaused4MoveImg = new boolean[groupNumMax];
			hasPaused4MoveImg[0] = false;
			hasPaused4MoveImg[1] = false;
			hasPaused4MoveImg[2] = false;
			hasPaused4MoveImg[3] = false;

			hasPaused4SendData = hasPaused4MoveImg;
			sleepTime = new int[groupNumMax];
			sleepTime[0] = 0;
			sleepTime[1] = 60;
			sleepTime[2] = 60;
			sleepTime[3] = 90;

			perGroupSportCnt = new int[groupNumMax]; // 锻炼次数
			perGroupSportCnt[0] = 12;
			perGroupSportCnt[1] = 10;
			perGroupSportCnt[2] = 8;
			perGroupSportCnt[3] = 6;

			forcePercent = new double[groupNumMax];
			forcePercent[0] = 0.6;
			forcePercent[1] = 0.7;
			forcePercent[2] = 0.8;
			forcePercent[3] = 0.9;
			mSettingForce
			.setText(getResources()
					.getString(
							R.string.exercise_setting_force,
							(int) (maxForce * forcePercent[whichGroupIsRunningFinished])));
			mIncreaseBtn.setVisibility(View.GONE);
			mDecreaseBtn.setVisibility(View.GONE);
			mSettingsBtn.setVisibility(View.GONE);

		} else if ((MODE_BODYBUILDING.equals(currentExerciseMode))
				|| (MODE_REDUCE_FAT.equals(currentExerciseMode))
				|| (mode_ConstantSpeed_active.equals(currentExerciseMode))
				|| (mode_ConstantSpeed_passive.equals(currentExerciseMode))
				|| (mode_ConstantForce_active.equals(currentExerciseMode))
				|| (mode_ConstantForce_passive.equals(currentExerciseMode))) {
			groupNumMax = 5;
			hasPaused4MoveImg = new boolean[groupNumMax];
			hasPaused4MoveImg[0] = false;
			hasPaused4MoveImg[1] = false;
			hasPaused4MoveImg[2] = false;
			hasPaused4MoveImg[3] = false;
			hasPaused4MoveImg[4] = false;
			hasPaused4SendData = hasPaused4MoveImg;
			sleepTime = new int[groupNumMax];
			sleepTime[0] = 0;
			sleepTime[1] = 30;
			sleepTime[2] = 30;
			sleepTime[3] = 25;
			sleepTime[4] = 20;
			forcePercent = new double[groupNumMax];
			forcePercent[0] = 0.5;
			forcePercent[1] = 0.45;
			forcePercent[2] = 0.4;
			forcePercent[3] = 0.35;
			forcePercent[4] = 0.35;
			perGroupSportCnt = new int[groupNumMax]; // 锻炼次数
			perGroupSportCnt[0] = 20;
			perGroupSportCnt[1] = 25;
			perGroupSportCnt[2] = 25;
			perGroupSportCnt[3] = 30;
			perGroupSportCnt[4] = 30;

			mSettingForce
			.setText(getResources()
					.getString(
							R.string.exercise_setting_force,
							(int) (maxForce * forcePercent[whichGroupIsRunningFinished])));
			mIncreaseBtn.setVisibility(View.GONE);
			mDecreaseBtn.setVisibility(View.GONE);
			mSettingsBtn.setVisibility(View.GONE);
		} else if (MODE_CUSTOMIZE.equals(currentExerciseMode)) {
			hasPaused4MoveImg = new boolean[groupNumMax];
			for (int i = 0; i < groupNumMax; i++) {
				hasPaused4MoveImg[i] = false;
			}
			hasPaused4SendData = hasPaused4MoveImg;
			sleepTime = new int[groupNumMax];
			// 组间隔时间
			for (int i = 0; i < groupNumMax; i++) {
				sleepTime[i] = 15;
			}
			forcePercent = new double[groupNumMax];
			// 设定锻炼力量
			for (int i = 0; i < groupNumMax; i++) {
				forcePercent[i] = custome[0];
			}
			perGroupSportCnt = new int[groupNumMax];
			// 锻炼次数
			for (int i = 0; i < groupNumMax; i++) {
				perGroupSportCnt[i] = (int) custome[3];
			}
			mSettingForce.setText(getResources().getString(
					R.string.exercise_setting_force,
					(int)forcePercent[whichGroupIsRunningFinished]));
			mIncreaseBtn.setVisibility(View.GONE);
			mDecreaseBtn.setVisibility(View.GONE);
			// mSettingsBtn.setVisibility(View.GONE);
		}
		mGroupNum.setText(getResources().getString(R.string.exercise_group_num,
				1));
		mTimes.setText(getResources().getString(R.string.exercise_time_num, 1));
		super.onResume();
		if (scale1 < 1) {
			secondParams = (int) (300 * scale1);
		} else {
			secondParams = 300;
		}
	}

	int exercise_count = 0;
	int group_count = 0; // 锻炼的组数
	int count = 5;

	@Override
	public void onClick(View v) {
		Log.d(TAG, "ExerciseActivity onClick");
		switch (v.getId()) {
		case R.id.exercise_back:
			if (isLineRunning) {
				new AlertDialog.Builder(this).setTitle(R.string.notice)
						.setMessage("请先终止训练！！！")
						.setPositiveButton(R.string.ok, null).show();
			} else {
				goBack();
			}
			break;
		case R.id.exercise_adjust:
			if (isLineRunning) {
				new AlertDialog.Builder(this).setTitle(R.string.notice)
						.setMessage("请先终止训练！！！")
						.setPositiveButton(R.string.ok, null).show();
			} else {
				AdjustSeatActivity.fromWhich = "exercise";
				Intent intent1 = new Intent(this, AdjustSeatActivity.class);
				startActivity(intent1);
				this.finish();
				overridePendingTransition(android.R.anim.fade_in,
						android.R.anim.fade_out);
			}
			break;
		case R.id.exercise_start_pause:// （开始——暂停 按钮）
			ClickStopButtonFlag=false;
			if (CountdownINGFlg) {
				Toast.makeText(this, "请等待计数完毕再操作！", Toast.LENGTH_LONG);
			} else {
				isLineRunning = !isLineRunning;
				// 正在训练
				if (isLineRunning) {
					// 计数完成标志（54321计数）
					if (countdownFinishFlg) {
						lineMoveThread = new LineMoveThread();
						lineMoveThread.start();
						sendDataThread = new SendDataThread();
						sendDataThread.start();
					} else {
						try {// 判断是否为自定义模式，选择力量设置，然后向下发送力量数据
							if (!MODE_CUSTOMIZE.equals(currentExerciseMode)) {

								settingForce = (int) (maxForce * forcePercent[whichGroupIsRunningFinished]);
								mOutputStream.write(CRCChecker
										.getFinalSendBytes(
												SET_SETTING_FORCE_PREFIX,
												settingForce));
								// 发送力量与发送模式之间间隔时间
								Thread.sleep(1000);
								if ((MODE_ADD_FORCE.equals(currentExerciseMode))
										|| (MODE_ADD_MUSCLE
												.equals(currentExerciseMode))
										|| (MODE_BODYBUILDING
												.equals(currentExerciseMode))
										|| (MODE_REDUCE_FAT
												.equals(currentExerciseMode))) {
									mOutputStream.write(CHANGE_WORK_STATE4);
								} else if (mode_ConstantSpeed_active
										.equals(currentExerciseMode)) {
									mOutputStream.write(CHANGE_WORK_STATE7);
								} else if (mode_ConstantSpeed_passive
										.equals(currentExerciseMode)) {
									mOutputStream.write(CHANGE_WORK_STATE8);
								} else if (mode_ConstantForce_active
										.equals(currentExerciseMode)) {
									mOutputStream.write(CHANGE_WORK_STATE9);
								} else if (mode_ConstantForce_passive
										.equals(currentExerciseMode)) {
									mOutputStream.write(CHANGE_WORK_STATE10);
								}
							} else {
								// 自定义模式
								settingForce = (int) (forcePercent[whichGroupIsRunningFinished]);
								mOutputStream.write(CRCChecker
										.getFinalSendBytes(
												SET_SETTING_FORCE_PREFIX,
												settingForce));
								Thread.sleep(1000);
								mOutputStream.write(CHANGE_WORK_STATE4);
							}
							sendDataFlag = 1;
						} catch (IOException e) {
							e.printStackTrace();
							IOMistake();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						// 计数线程开启
						CountDownThread countDownThread = new CountDownThread();
						countDownThread.start();
					}
					// 是正在训练，将第三个按钮设置为暂停按钮
					mPauseBtn.setText(getResources().getString(
							R.string.exercise_pause));
					Log.d(TAG, "exercise_pause click");
				} else {// 不是正在训练，将第三个按钮设置为开始按钮
					mPauseBtn.setText(getResources().getString(R.string.start));
				}
			}
			break;

		case R.id.exercise_stop:
			ClickStopButtonFlag=true;
			if (CountdownINGFlg) {
				Toast.makeText(this, "请等待计数完毕再操作！", Toast.LENGTH_LONG);
			} else {
				isLineRunning = false;
				isGroupRunningFinished = false;
				countdownFinishFlg = false;
				mPauseBtn.setText(getResources().getString(R.string.start));
				if (myLineImageView1 != null) {
					frameLayout.removeView(myLineImageView1);
					myLineImageView1 = null;
				}
				if (myLineImageView2 != null) {
					frameLayout.removeView(myLineImageView2);
					myLineImageView2 = null;
				}
				hasPaused4SendData = hasPaused4MoveImg;
				whichGroupIsRunningFinished = 0;
				if (!MODE_CUSTOMIZE.equals(currentExerciseMode)) {
					// init thread data
					hasPaused4MoveImg[0] = false;
					hasPaused4MoveImg[1] = false;
					hasPaused4MoveImg[2] = false;
					hasPaused4MoveImg[3] = false;
					if (!MODE_ADD_MUSCLE.equals(currentExerciseMode)) {
						// 增肌模式下不存在，所以不执行。
						hasPaused4MoveImg[4] = false;
					}
					mSettingForce
							.setText(getResources()
									.getString(
											R.string.exercise_setting_force,
											(int) (maxForce * forcePercent[whichGroupIsRunningFinished])));
				} else {
					for (int i = 0; i < groupNumMax; i++) {
						hasPaused4MoveImg[i] = false;
					}
					mSettingForce.setText(getResources().getString(
							R.string.exercise_setting_force,
							(int) forcePercent[whichGroupIsRunningFinished]));
				}
				exercise_count = 0;

				mGroupNum.setText(getResources().getString(
						R.string.exercise_group_num, 1));
				mTimes.setText(getResources().getString(
						R.string.exercise_time_num, 1));

				ball.cy = secondParams;
				ball.invalidate();
				ball.setVisibility(View.GONE);

				Toast toast = Toast.makeText(this, "Resetting...",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				try {
					mOutputStream.write(CHANGE_WORK_STATE0);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				}

				try {
					Thread.sleep(800);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Toast toast2 = Toast.makeText(this, "Reset successs",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
			}
			break;

		case R.id.exercise_increase:
			if (isLineRunning) {
				new AlertDialog.Builder(this).setTitle(R.string.notice)
						.setMessage("请先点击暂停或者终止训练！！！")
						.setPositiveButton(R.string.ok, null).show();
			} else {
				try {
					if (settingForce < 200) {
						settingForce = settingForce + 5;
						mSettingForce.setText("" + settingForce);
					}
					mOutputStream.write(CRCChecker.getFinalSendBytes(
							SET_SETTING_FORCE_PREFIX, settingForce));
					Thread.sleep(100);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			break;

		case R.id.exercise_decrease:
			if (isLineRunning) {
				new AlertDialog.Builder(this).setTitle(R.string.notice)
						.setMessage("请先点击终止训练！！！")
						.setPositiveButton(R.string.ok, null).show();
			} else {
				try {
					if (settingForce > 14) {
						settingForce = settingForce - 5;
						mSettingForce.setText("" + settingForce);
					}
					mOutputStream.write(CRCChecker.getFinalSendBytes(
							SET_SETTING_FORCE_PREFIX, settingForce));
					Thread.sleep(100);
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			break;

		case R.id.exercise_settings:
			isLineRunning = false;
			Intent intent = new Intent(this, CustomizeModeActivity.class);
			startActivity(intent);
			this.finish();
			break;
		default:
			break;
		}
	}

	SendStateThread sendStateThread;

	private void goBack() {
		if (!MODE_CUSTOMIZE.equals(currentExerciseMode)) {
			isLineRunning = false;
			Intent intent = new Intent(this, SelectModeActivity.class);
			startActivity(intent);
			this.finish();
		} else {
			isLineRunning = false;
			Intent intent = new Intent(this, ControlPanelActivity.class);
			startActivity(intent);
			this.finish();
		}
	}

	@Override
	public void onBackPressed() {
		goBack();
	}

	Handler mHandler = new Handler();

	class CountDownThread extends Thread {
		int count = 6;

		public void run() {
			mtop = frameLayout.getTop() + 40;
			mbottom = frameLayout.getBottom();
			scrollLineCount = (int) (imageW * 1.5);
			CountdownINGFlg = true;
			do {
				try {
					if (count > 0) {
						mCountdown5.setVisibility(View.VISIBLE);
						mHandler.obtainMessage(COUNT_DOWN54321, count)
								.sendToTarget();
						Thread.sleep(1000);
						count--;
					} else {
						mHandler.obtainMessage(COUNT_DOWN54321_FINISH)
								.sendToTarget();
						lineMoveThread = new LineMoveThread();
						lineMoveThread.start();
						isLineRunning = true; // dong
						CountdownINGFlg = false;
						countdownFinishFlg = true;
						sendDataThread = new SendDataThread();
						isPauseFlg = false; // dong
						sendDataThread.start();
					}
				} catch (Exception e) {
					Log.d(TAG, "mCountdown5", e);
				}
			} while (!countdownFinishFlg);
		}
	}

	class SendDataThread extends Thread {
		public void run() {
			do {
				try {
					if (isPauseFlg
							&& !hasPaused4SendData[whichGroupIsRunningFinished]) {
						sleep(sleepTime[whichGroupIsRunningFinished]);
						isPauseFlg = false;
						hasPaused4SendData[whichGroupIsRunningFinished] = true;
					}
					int ReciveOverTime = 0;
					while (sendDataFlag != 0 && ReciveOverTime < 100) {
						ReciveOverTime++;
						Thread.sleep(1); // dong add
					} 
					mOutputStream.write(GET_BALL_LOCATION);
					sendDataFlag = 2;
				} catch (IOException e) {
					e.printStackTrace();
					IOMistake();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} while (countdownFinishFlg && isLineRunning && !isInterrupted()
					&& !isPauseFlg);
		}
	}

	boolean isGroupRunningFinished = false;

	class LineMoveThread extends Thread {
		@Override
		public void run() {
			do {
				try {
					if (!isGroupRunningFinished) { // 所有的组完毕后就不让线程执行
						if (isPauseFlg
								&& !hasPaused4MoveImg[whichGroupIsRunningFinished]) {
							isLineRunning = false;
							sleep(sleepTime[whichGroupIsRunningFinished] * 50);
							isPauseFlg = false;
							hasPaused4MoveImg[whichGroupIsRunningFinished] = true;
							mHandler.obtainMessage(UPDATE_LINE_HEADER_TEXT)
									.sendToTarget();
						} else {
							// 修改后的
							Thread.sleep(scrollLineTime);
							mHandler.obtainMessage(MOVE_LINE).sendToTarget();
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} while (isLineRunning==true&&ClickStopButtonFlag==false);
		}
	}

	@SuppressWarnings("static-access")
	public void change() {
		// int ballx = 400;
		int bally = ball.cy;
		if (((scrollLineCount - scrollLineCountDiv / 2) / scrollLineCountDiv) % 2 == 0) {
			xyscale = myLineImageView2.getWidth() / imageW;
		} else {
			xyscale = myLineImageView1.getWidth() / imageW;
		}
		int imagex = (int) (scrollLineCount-75 - imageW * 1.5)
				% scrollLineCountDiv;
		if (imagex <= 0) {
			imagex = 1;
		}
		//int imagey = (int) ((int) (bally - 100) * 1.5 + 100);
		int imagey=(int) (60+(230*(bally-100))/210);
		// 根据View坐标获取图片RGB
		int i = 0;
		if (imagey <=300 && imagey >= 0) {
			if(imagey==300){imagey=299;}
			i = bitmap.getPixel(imagex, imagey);
			//mSettingForce.setText(bitmap.getWidth()+"");
		}
		//mGroupNum.setText("" + i);
		// 根据RGB值判断change的值从来选择重绘小球颜色
		if (i != 0) {
			ball.change = 0;
		} else {
			ball.change = 1;
		}
		ball.invalidate();
	}

	@Override
	protected void onDataReceived(final byte[] buffer, final int index,
			final int packlen) {
		final byte[] crctest = new byte[packlen];
		for (int i = 0; i < packlen; i++) {
			crctest[i] = buffer[i];
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (CRCChecker.checkBuf(crctest)) {
					if (sendDataFlag == 2&& isLineRunning==true) {
						int x = (int) crctest[4];
						int y = (int) crctest[3];
						if (x < 0) {
							x += 256;
						}
						if (y < 0) {
							y += 256;
						}
						y = y * 256 + x;
						ball.cy = (int) (310 - 210 * y / position);
						change();
					}
					sendDataFlag = 0;
				}
			}
		});
	}

	public void testPosAndForce(String title, String option) {
		AlertDialog.Builder test = new AlertDialog.Builder(
				ExerciseActivity.this);
		test.setTitle(title);
		test.setIcon(android.R.drawable.ic_dialog_info);
		test.setPositiveButton("返回测试", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(ExerciseActivity.this,
						ControlPanelActivity.class);
				startActivity(intent);
				ExerciseActivity.this.finish();
			}
		});
		test.setNegativeButton(option, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				defaultposition.show();
				maxForce = 100;
			}
		});
		test.show();
	}

	class SendStateThread extends Thread {
		// 要发送的第一个数据 发送次数
		int sendCount1;
		// 第一个数据 接收得到的返回值
		public String receviedStr1;
		// 要发送的第二个数据 发送次数
		int sendCount2;
		// 第二个数据 接收得到的返回值
		public String receviedStr2;
		// 第一个数据 发送是否成功（接收到正确的返回值才算成功）
		public boolean is1Finished;

		public SendStateThread() {
			// 构造函数初期化
			sendCount1 = 0;
			receviedStr1 = "";
			sendCount2 = 0;
			receviedStr2 = "";
			is1Finished = false;
		}

		@Override
		public void run() {

			while (true) {
				try {
					// 第一个数据没发送完成，并且，发送次数小于3， 并且，接收得到的返回值还是""
					// 此时，继续发送数据，并把发送次数加1
					if (!is1Finished && sendCount1 < 3
							&& "".equals(receviedStr1)) {
						mOutputStream.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, settingForce));
						sendCount1++;
					}
					// 第一个数据发送完得到的返回值判断，不为""，则认为发送接收都成功
					if (!"".equals(receviedStr1)) {
						// 第一个数据 发送是否成功的标志设置为true
						is1Finished = true;
					}
					// 第一个数据发送完成，并且，第二个数据发送次数小于3， 并且，第二个数据接收得到的返回值还是""
					if (is1Finished
							&& (sendCount2 < 3 && !"".equals(receviedStr2))) {
						mOutputStream.write(CRCChecker.getFinalSendBytes(
								SET_SETTING_FORCE_PREFIX, settingForce));
						sendCount2++;
					}

					if (sendCount2 >= 3 && "".equals(receviedStr2)) {
						mHandler.obtainMessage(SEND_FAILED).sendToTarget();
					}
					sleep(50);
				} catch (Exception e) {
				}
			}
		}
	}

}
